package com.lagou.rocketmq.task.listener;

import com.alibaba.fastjson.JSON;
import com.lagou.rocketmq.task.constant.RedisKey;
import com.lagou.rocketmq.task.dao.OrderDao;
import com.lagou.rocketmq.task.dao.ProductDao;
import com.lagou.rocketmq.task.enumration.OrderStatusEnum;
import com.lagou.rocketmq.task.model.entity.OrderDO;
import com.lagou.rocketmq.task.model.event.CheckOrderPayEvent;
import com.lagou.rocketmq.task.model.event.CreateOrderEvent;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * 创建订单事件消费者
 *
 */
@Component
@RocketMQMessageListener(topic = "seckilling_create_order", consumerGroup = "consumer_grp_01")
public class CreateOrderListener implements RocketMQListener<String> {

    private static Logger logger = LoggerFactory.getLogger(CreateOrderListener.class);

    @Autowired
    private JedisPool jedisPool;

    @Autowired
    private OrderDao orderDao;

    @Autowired
    private ProductDao productDao;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public void onMessage(String message) {
        // 处理broker推送过来的消息
        logger.info("接收到创建订单消息" + message);
        CreateOrderEvent createOrderEvent = JSON.parseObject(message, CreateOrderEvent.class);
        Integer productId = createOrderEvent.getProductId();

        // 扣减库存
        String productInventoryKey = RedisKey.getProductInventoryKey(productId);
        try (Jedis jedis = jedisPool.getResource()) {
            Long decr = jedis.decr(productInventoryKey);
            // 库存已经小于0
            if (decr < 0L) {
                logger.info("库存小于0，创建订单消息：{}", createOrderEvent);
                return;
            }
        }

        // 扣减数据库库存
        int count = productDao.decrProductInventory(productId);
        if (count <= 0) {
            logger.info("数据库扣减失败");
            return;
        }

        // 持久化订单信息
        OrderDO orderDO = new OrderDO();
        orderDO.setCustomerId(createOrderEvent.getProductId());
        orderDO.setProductId(productId);
        orderDO.setStatus(OrderStatusEnum.NOT_PAY.getValue());
        orderDao.save(orderDO);
        logger.info("创建订单成功,订单信息：{}", orderDO);

        // 发送延迟检测付款事件
        CheckOrderPayEvent checkOrderPayEvent = new CheckOrderPayEvent();
        checkOrderPayEvent.setOrderId(orderDO.getId());
        rocketMQTemplate.syncSend("seckilling_check_pay_order", MessageBuilder.withPayload(
            JSON.toJSONString(checkOrderPayEvent)).build(), 2000, 6);
    }
}
